package com.example.shixun2;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
public class MessageHistoryAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    // 1. 定义两个常量
    private static final int VIEW_TYPE_SENT = 1;        //发送者标识符
    private static final int VIEW_TYPE_RECEIVED = 2;   //接收者标识符

    private List<Message> messageList;      //消息列表的构建

    //为“发送”布局创建ViewHolder
    public static class SentMessageHolder extends RecyclerView.ViewHolder {
        TextView messageText;
        public SentMessageHolder(@NonNull View itemView) {
            super(itemView);
            //获取绑定布局文件中的TextView
            messageText = itemView.findViewById(R.id.tv_message_text);
        }
    }

    // 为“接收”的布局 创建一个 ViewHolder
    public class ReceivedViewHolder extends RecyclerView.ViewHolder {
        TextView messageText;

        public ReceivedViewHolder(@NonNull View itemView) {
            super(itemView);
            messageText = itemView.findViewById(R.id.tv_message_text);
        }
    }

    public MessageHistoryAdapter(List<Message> messageList) {
        this.messageList = messageList;
    }

    // 根据消息的isSent属性，返回不同的ViewHolder，从而创建不同的布局
    @Override
    public int getItemViewType(int position) {
        Message message = messageList.get(position);
        if (message.isSent()) {
            return VIEW_TYPE_SENT;
        } else {
            return VIEW_TYPE_RECEIVED;
        }
    }

    // 根据ViewType创建不同的ViewHolder
    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        if (viewType == VIEW_TYPE_SENT) {
            // 加载“发送”布局
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.item_message_bubble_sent, parent, false);
            return new SentMessageHolder(view);
        } else {
            // 加载“接收”布局
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.item_message_bubble_received, parent, false);
            return new ReceivedViewHolder(view);
        }
    }

    // 绑定数据
    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        Message message = messageList.get(position);

        if (holder.getItemViewType() == VIEW_TYPE_SENT) {
            // 绑定“发送”的数据
            SentMessageHolder sentHolder = (SentMessageHolder) holder;
            sentHolder.messageText.setText(message.getText());
        } else {
            // 绑定“接收”的数据
            ReceivedViewHolder receivedHolder = (ReceivedViewHolder) holder;
            receivedHolder.messageText.setText(message.getText());
        }
    }

    // 返回要消息列表的长度
    @Override
    public int getItemCount() {
        return messageList.size();
    }
}
